package com.usian.paymentdemo.util;

import com.usian.paymentdemo.config.WxPayConfig;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.refund.model.RefundNotification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author YangRenyu
 */
@Component
public class WechatPayValidatorUtils {

    @Autowired
    private Config config;

    private RequestParam requestParam(HttpServletRequest request, String body){
        // 获取各种支付参数
        String serial = request.getHeader("Wechatpay-Serial");
        String signature = request.getHeader("Wechatpay-Signature");
        String nonce = request.getHeader("Wechatpay-Nonce");
        String timestamp = request.getHeader("Wechatpay-Timestamp");
        return new RequestParam.Builder()
                .serialNumber(serial)
                .nonce(nonce)
                .signature(signature)
                .timestamp(timestamp)
                .body(body)
                .build();
    }

    private  NotificationParser initvalidateInfo() {
            // 初始化 NotificationParser
            return  new NotificationParser((NotificationConfig) config);
    }

    /**
     * 支付回调验签与解密
     * @param request
     * @param body
     * @return
     */
    public final Transaction payValidate(HttpServletRequest request, String body){
        // 以支付通知回调为例，验签、解密并转换成 Transaction
        return  this.initvalidateInfo()
                .parse(this.requestParam(request,body), Transaction.class);
    }

    /**
     * 退款回调验签与解密
     * @param request
     * @param body
     * @return
     */
    public final RefundNotification reFundValidate(HttpServletRequest request, String body){
        // 以支付通知回调为例，验签、解密并转换成 Transaction
        return  this.initvalidateInfo()
                .parse(this.requestParam(request,body), RefundNotification.class);
    }


}
